#!/usr/bin/env Rscript

## ####################
## Package Dependencies
## ####################

suppressMessages({
    library("foreach")
    library("wnominate")
    library("doRNG")
    library("plyr")
}
                 )

## ##############
## Define Handoff
## ##############

BATON <- new.env()

## ################
## Env Dependencies
## ################

set.seed(1)
isDistMem <- as.integer(Sys.getenv("DISTMEM"))
nProcs <- as.integer(Sys.getenv("PROCS"))
nMC <- as.integer(Sys.getenv("MC"))

## #########
## Set Paths
## #########

p2root <- "../../../"
p2output <- paste(p2root, "data/CSV/mc/other.csv", sep = "")

## DGP Function
source(paste(p2root, "src/R/functions/simulator.R", sep = ""), local = BATON)

## For setting DGP of MC
p2estimates <- paste(p2root, "data/RDATA/estimates2/", sep = "")
load(paste(p2estimates, "hou112.Rdata", sep = ""), BATON)

## #################
## Data Dependencies
## #################

dfCombosA <- data.frame(N = 500,
                        J = c(50, 100, 250, 500, 10e2, 15e2, 20e2, 25e2, 50e2),
                        group = "N"
                        )

dfCombosB <- data.frame(N = c(50, 100, 250, 500, 10e2, 2500, 5000, 75e2, 100e2),
                        J = 1000,
                        group = "J"
                        )

dfCombos <- rbind(dfCombosA,
                  dfCombosB
                  )



dfGrid <- ddply(dfCombos,
                c("N", "J", "group"),
                function(df) data.frame(MC = 1:nMC)
                )

BATON$dfGrid <- dfGrid

## ############################
## Shared or Distributed Memory
## ############################

if (isDistMem == 1) {
    library(doMPI)
    cl <- startMPIcluster()
    registerDoMPI(cl)
} else {
    library("doMC")
    registerDoMC(nProcs)
    BATON$threads <- nProcs
}
registerDoRNG()

## #########
## MC Trials
## #########
dfOut <- foreach(g = 1:nrow(dfGrid),
                 .combine = rbind,
                 .export = "BATON",
                 .errorhandling = "remove",
                 .multicombine = FALSE
                 )  %dopar% {
                     attach(BATON)
                     require("FastEst")
                     require("wnominate")
                     print(dfGrid[g, ])
                     thisN <- dfGrid$N[g]
                     thisJ <- dfGrid$J[g]
                     thisMC <- dfGrid$MC[g]
                     thisGroup <- dfGrid$group[g]
                     thisData <- generateData(out$xbar,
                                              out$betabar,
                                              thisN,
                                              thisJ,
                                              2
                                              )

                     wtimes <- system.time({
                         wout <- wnominate(thisData$rc1,
                                           dims = 1,
                                           polarity = 1,
                                           trials = 1
                                           )
                     }
                                           )
                     thisDF <- data.frame(type = c("wnominate"),
                                          times = c(wtimes[3]),
                                          fit = c(wout$fits[1]/100),
                                          N = thisN,
                                          J = thisJ,
                                          MC = thisMC,
                                          group = as.character(thisGroup)
                                          )
                     return(thisDF)
                 }

write.csv(dfOut, file = p2output)

if (isDistMem == 1) {
    closeCluster(cl)
    mpi.quit()
}
